package com.ajouroid.smartcoworker;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.android.gcm.GCMRegistrar;

public class LoginActivity extends Activity implements OnClickListener {

	EditText tb_id;
	EditText tb_pwd;

	Button btn_login;
	Button btn_registration;
	//뒤로 두번눌러 종료 구현
	private boolean m_bFlag = false;
	private Handler mBackClickHandler;
	final String TAG = "LoginActivity"; 

	final String SENDER_ID = "1016502050851";

	final String ONREGISTER = "com.ajouroid.smartcoworker.ON_REGISTERED";

	String regId;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		setContentView(R.layout.activity_login);

		mBackClickHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				if(msg.what == 0) {
					m_bFlag = false;
				}
			}
		};

		tb_id = (EditText)findViewById(R.id.login_et_id);
		tb_pwd = (EditText)findViewById(R.id.login_et_pwd);

		btn_login = (Button)findViewById(R.id.login_btn_login);
		btn_registration = (Button)findViewById(R.id.login_btn_registration);




		GCMRegistrar.checkDevice(this);
		GCMRegistrar.checkManifest(this);
		regId = GCMRegistrar.getRegistrationId(this);

		registerReceiver(regReceiver, new IntentFilter(ONREGISTER));

		if (regId.equals(""))
		{
			GCMRegistrar.register(this, SENDER_ID);
			Log.d(TAG,"Registering...");
		}
		else
		{
			Log.d(TAG,"Already Registered : " + regId);
		}
	}
	
	public boolean onKeyDown(int KeyCode, KeyEvent event){
		super.onKeyDown(KeyCode, event);

		if(event.getAction() == KeyEvent.ACTION_DOWN) {
			switch(KeyCode) {
			case KeyEvent.KEYCODE_BACK:	// `뒤로` 키와 같은 기능을 한다.
				if(!m_bFlag) {
					Toast.makeText(getApplicationContext(), "'뒤로'버튼을 한번 더 누르시면 종료됩니다",     Toast.LENGTH_SHORT).show();
					m_bFlag = true;
					mBackClickHandler.sendEmptyMessageDelayed(0, 2000);

					return false;
				}
				else {
					DeleteCache del = new DeleteCache();
					del.clearCache(this);
					finish();
				}
				return true;
			}
		}

		return false;
	}

	@Override
	public void onResume()
	{
		super.onResume();
		btn_registration.setOnClickListener(
				new OnClickListener() {
					public void onClick(View arg0) {
						Intent regIntent = new Intent(LoginActivity.this, RegisterActivity.class);

						startActivity(regIntent);
					}
				});

		btn_login.setOnClickListener(
				new OnClickListener() {
					public void onClick(View arg0) {
						LoginTask task = new LoginTask(LoginActivity.this);
						String key = GCMRegistrar.getRegistrationId(LoginActivity.this);
						if (!regId.equals(""))
							task.execute(tb_id.getText().toString(), tb_pwd.getText().toString(), key);
					}
				});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		return true;
	}

	@Override
	public void onDestroy()
	{
		super.onDestroy();

		unregisterReceiver(regReceiver);
	}

	public void onClick(View arg0) {

	}



	public class LoginTask extends AsyncTask<String, Void, String>
	{
		Context mCtx;
		String id;
		ProgressDialog login;

		public LoginTask(Context context)
		{
			mCtx = context;
		}

		@Override
		protected String doInBackground(String... arg) {

			//HttpConnector.setAddress(et_address.getText().toString());

			HttpConnector conn = new HttpConnector();

			Map<String, String> msg = new HashMap<String,String>();
			msg.put("type", "login");

			id = arg[0];
			msg.put("id", arg[0]);
			msg.put("password", arg[1]);
			msg.put("key", arg[2]);
			msg.put("device", "android");

			String resp = conn.post("Login", msg);
			return resp;
		}

		@Override
		protected void onPostExecute(String result) {

			try {
				JSONObject obj = new JSONObject(result);

				String status = obj.getString("status");

				if (status.equals("ok"))
				{
					Intent activity = new Intent(mCtx, InitialActivity.class);

					String name = obj.getString("name");
					String email = obj.getString("email");
					String image = obj.getString("image");

					activity.putExtra("id", id);
					activity.putExtra("name", name);
					activity.putExtra("email", email);
					activity.putExtra("image", image);

					mCtx.startActivity(activity);
					finish();
				}
				else if (status.equals("fail"))
				{
					Toast.makeText(mCtx, "Wrong Account.", Toast.LENGTH_SHORT).show();
				}
				else
				{
					Toast.makeText(mCtx, "Error: " + status, Toast.LENGTH_SHORT).show();
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (NullPointerException ne) {
				ne.printStackTrace();
			}
			super.onPostExecute(result);
			login.dismiss();
		}

		@Override
		protected void onPreExecute() {
			login = new ProgressDialog(mCtx);
			login.setTitle("Wait please...");
			login.setMessage("Now Loding...");
			login.setCancelable(false);
			login.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			
			login.show();
			
			super.onPreExecute();
		}
	}

	BroadcastReceiver regReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			String id = intent.getStringExtra("regId");

			regId = id;
		}

	};
}
